#include "../inc/skyObject.h"
#include "../inc/skyString.h"
#include "../inc/skyStd.h"

namespace Sky
{
	Void* Memory::alloc( size_t size )
	{
		alloc_count ++;
		//return ::malloc(size);
		
		Void* p = ::new u8[size];
		//xInfor2A("alloc %x size %d",p,size);
		return p;
	}

	Void Memory::free( Void* p )
	{

		free_count ++;
		//::free(p);
		//xInfor1A("freed %x",p);
		::delete p;
		return;
	}

	Void Memory::copy( Void* dst,const Void* src,size_t size )
	{
		memcpy(dst,src,size);
		return;
	}

	Void*  Memory::operator new( unsigned int size )
	{
		return Memory::alloc(size);
	}

	Void*  Memory::operator new[]( unsigned int size )
	{
		return Memory::alloc(size);
	}

	Void* Memory::clone( size_t size,const Void* src )
	{
		Void* p = alloc(size);
		if( p == vNull)return vNull;
		copy(p,src,size);
		return p;
	}

	Void* Memory::realloc( Void* p,size_t size )
	{
#ifdef realloc
		Void* pnew = ::realloc(p,size);
		xAssert(pnew);
		if( pnew == vNull)
		{
			free(p);
			return vNull;
		}
		return pnew;
#else
        xAssert("not implemented");
        return vNull;
#endif
	}

	Void Memory::set( Void* dst,u32 n,size_t size )
	{
		::memset(dst,n,size);
	}

	int Memory::free_count = 0;

	int Memory::alloc_count = 0;

	void  Memory::operator delete( void* p )
	{
		return Memory::free(p);
	}

	void  Memory::operator delete[]( void* p )
	{
		return Memory::free(p);
	}

	PtrWrapper::~PtrWrapper()
	{
		if(ptr)ptr->decRef();
	}

	StringPtr Object::toString(StringPtr str)
	{
		Char* p = instName();
		String::staticString s(p);
		if(!str)
			str = skynew(String());
		*str = String(s);
		return str;
	}

	Void Object::incRef()
	{
		if(!isOnHeap())return;
		_ref++;
		return ;
	}

	Void Object::decRef()
	{
		if(!isOnHeap())return;
		--_ref;
		if(_ref == 0)
		{
			delete this;
			return ;
		}
		return ;
	}

	Object::~Object()
	{
		//std::cout<<"deleted: --->"<<std::endl;
	}

	Object::Object() :_ref(0x80000000)
	{
		//std::cout<<"created:---<"<<std::endl;
	}


}
